
'''
pip install flask
pip install flask-cors
'''
import json
import time
from flask import Flask, Response # , request, jsonify, render_template
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 允许跨域

def generate():
    id = 0
    event = 'message'
    count = 0
    while True:
        time.sleep(1)  # 模拟一些工作
        yield f"id: {id}\nevent: {event}\nretry: {3000}\ndata: {{\"message\": \"{count}\"}}\n\n"
        count += 1
        id += 1

@app.route('/sse', methods=['GET'])
def sse():
    return Response(generate(), mimetype='text/event-stream')

@app.route('/sse2', methods=['POST'])
def sse2():
    return Response(generate(), mimetype='text/event-stream')

@app.route('/stream', methods=['POST'])
def stream():
    id = 1
    event = 'message'
    messages = ['如下：', '[', '\t{\'name\':\'zs\', \'age\':19},', '\t{\'name\':\'ls\', \'age\':22}', ']']
    def eventStream():
        # id = 0
        # while True:
        for message in messages:
            # wait for source data to be available, then push it
            yield 'id: {}\nevent: {}\nretry: {}\ndata: {}\n\n'.format(id, event, 3000, message)
        # yield 'id: {}\nevent: {}\ndata: {}\n\n'.format(id, event, '你好')
    return Response(eventStream(), mimetype="text/event-stream")


@app.route('/stream2', methods=['POST'])
def stream2():
    # id = 1
    event = 'message'
    ss = [{'name': 'zs', 'age': 19}, {'name': 'ls', 'age': 22}]
    messages = ['如下：', '[\n']
    for i in range(len(ss)):
        if i < len(ss) - 1:
            messages.append('\t' + str(ss[i]) + ',\n')
        else:
            messages.append('\t' + str(ss[i]) + '\n')
    messages.append(']')
    def eventStream():
        id = 0
        # while True:
        for message in messages:
            # wait for source data to be available, then push it
            id += 1
            yield 'id: {}\nevent: {}\nretry: {}\ndata: {}\n'.format(id, event, 3000, message)
        id += 1
        yield 'id: {}\nevent: {}\nretry: {}\ndata: {}\n'.format(id, event, 3000, 'end')    
    return Response(eventStream(), mimetype="text/event-stream")


if __name__ == '__main__':
    # app.run()
    app.run(port=8080, host="0.0.0.0", debug=True)
